package com.csu.mall.product.exception;

import com.csu.mall.common.utils.R;
import com.csu.mall.product.Global;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.csu.mall.product.controller")
public class mallGlobalException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)//@ExceptionHandler表示方法能处理的异常类型
    public R handleValidException(MethodArgumentNotValidException e){
        //通过bindingResult拿到校验异常的字段和校验信息
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item->{
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        return  R.error(Global.StatusCode.VALID_EXCEPTION.getCode(), Global.StatusCode.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

    @ExceptionHandler(Throwable.class) //处理任意异常的方法
    public R handleThrowable(Throwable e){
        return R.error();
    }
}
